package com.ruoyi.common.utils.ping;

/**
 * @Author: XRW
 * @CreateTime: 2023-11-09  15:45
 */
import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ServerHealthChecker {

    public static void main(String[] args) {
        // Define a list of server addresses
        String[] serverAddresses = {"server1.example.com", "server2.example.com"};

        // Define the check frequency (e.g., every 5 minutes)
        long checkInterval = 5 * 60 * 1000;

        // Create a scheduled task to check server health
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(serverAddresses.length);
        for (String serverAddress : serverAddresses) {
            executor.scheduleAtFixedRate(() -> {
                int isServerHealthy = isServerHealthy(serverAddress);
                System.out.println(serverAddress + " is healthy: " + isServerHealthy);
                // You can implement alerting logic here
            }, 0, checkInterval, TimeUnit.MILLISECONDS);
        }
    }

    private static int isServerHealthy(String serverAddress) {
        try {
            InetAddress address = InetAddress.getByName(serverAddress);
            if (address.isReachable(5000)){
                return 1;
            }; // 5000ms timeout
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
